package com.mic.yzzn.plc.common.instructions.request;

import com.mic.yzzn.plc.common.ins.datastructure.PLCContactorNumber;
import com.mic.yzzn.plc.common.instructions.basic.PLCRequestInstruction;
import org.apache.commons.lang.StringUtils;

public class PLCMultipleContactorReadInstruction extends PLCMultipleContactorInstruction
{
	/**
	 * 初始化方法
	 */
	public PLCMultipleContactorReadInstruction()
	{
		requestCode = PLCRequestInstruction.READ_PLURAL_CONTACTOR_INS;
	}
	
	@Override
	public String initWithString(String instructionString) throws IllegalArgumentException
	{
		String tempResult = super.initWithString(instructionString);

    	// 判断请求码与当前指令的请求码是否符合
    	int requestCodeLength = requestCode.length();
    	if (!(StringUtils.substring(tempResult, 0, requestCodeLength).equals(requestCode)))
		{
			throw new IllegalArgumentException("PLCSingleContactorReadInstruction's requestCode must be \"" + requestCode +"\"");
		}
    	
    	// 截取请求码
    	tempResult = StringUtils.substringAfter(tempResult, requestCode);

    	// 读取触点数量
		int c = Integer.parseInt(tempResult.substring(0, 1));
    	setCount(c);
    	// 截取触点数量
    	tempResult = tempResult.substring(1);

		// 检测读取触点数量是否错误
		if (c != tempResult.length() / 5)
		{
			throw new IllegalArgumentException("PLCSingleContactorReadInstruction's count must equal to the number of contactorCode and contactorNumber");
		}
		
    	// 取得触点代码和触点编号
    	int codeBegin = 0;
    	for (int i = 0; i < count; ++i)
    	{
    		codeBegin = i * 5;
    		// 设置触点代码
    		String contactorCode = tempResult.substring(codeBegin, codeBegin + 1);
    		String cNumber = tempResult.substring(codeBegin + 1, codeBegin + 1 + 4);
    		// 设置触点编号
    		PLCContactorNumber contactorNumber = new PLCContactorNumber(cNumber.substring(0, 3), cNumber.charAt(3));
    		
    		contactorCodes.add(contactorCode);
    		contactorNumbers.add(contactorNumber);
    	}
		
    	tempResult = tempResult.substring(5 * count);
    	
		return tempResult;
	}

	@Override
	public String toString()
	{
		return super.toString();
	}
}
